#include "ipc.h"
void consume(int cho)
{
	while(1){
		switch(cho){
			case 0:
				P(TP_Csyn_sem);
				P(TP_Cmtx_sem);
				printf("%d吸烟者有胶水G,取到烟草%c,纸张%c,开始吸烟...\n",getpid(),tobacco[0],paper[0]);
				V(TP_Cmtx_sem);
				V(TP_Psyn_sem);
			break;
			case 1:
				P(GT_Csyn_sem);
				P(GT_Cmtx_sem);
				printf("%d吸烟者有纸张P,取到胶水%c,烟草%c,开始吸烟...\n",getpid(),glue[0],tobacco[0]);
				V(GT_Cmtx_sem);
				V(GT_Psyn_sem);
			break;
			case 2:
				P(PG_Csyn_sem);
				P(PG_Cmtx_sem);
				printf("%d吸烟者有烟草T,取到纸张%c,胶水%c,开始吸烟...\n",getpid(),paper[0],glue[0]);
				V(PG_Cmtx_sem);
				V(PG_Psyn_sem);
			break;
		}
	}
}
int main(int argc,char * argv[])
{
	//可在在命令行第一参数指定一个进程睡眠秒数,以调解进程执行速度
	if(argv[1] != NULL) rate = atoi(argv[1]);
	else rate = 1; //不指定为1秒
	signal(SIGINT,(sighandler_t)sigcat); //注册一个本进程处理键盘中断的函数
	//初始化同步机制
	ipc_init();
	int pid;
	int status;
	//for(int i=0;i<3;i++){		
	pid=fork();
	if(pid<0){
		perror("fork error!");
		exit(EXIT_FAILURE);
	}else if(pid==0){
		consume(0);
	}else{
		pid=fork();
		if(pid<0){
			perror("fork error!");
			exit(EXIT_FAILURE);
		}else if(pid==0){
			consume(1);
		}else{
			pid=fork();
			if(pid<0){
				perror("fork error!");
				exit(EXIT_FAILURE);
			}else if(pid==0){
				consume(2);
			}else{
				waitpid(pid,&status,0);
			}
		}	
	}
	return 0;
}
